import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaForm, WeaSwitch, WeaTableNew } from 'comsMobx';
import { toJS } from 'mobx';
import { Synergy } from '../components/Portal/Portal';
import {
  WeaTop,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaDropMenu,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaTab,
  WeaFormItem,
  WeaSearchGroup,
  WeaDialog,
  WeaBrowser,
  WeaLocaleProvider,
  WeaMoreButton,
} from 'ecCom';
import { Spin, Button, Modal } from 'antd';

const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
@inject('docDummyStore')

@observer
class Dummy extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      searchType:['base', 'advanced']
    }
  }
  componentDidMount() {
    const { docDummyStore } = this.props;
    const { dummyId } = this.props.location.query;
    docDummyStore.setDummyId(dummyId);
    const { getConditionInfo, doSearch
      , getTreeData, getchooseDummy } = docDummyStore;
    getTreeData();
    getConditionInfo('Dummy');
    getchooseDummy();
  }
  componentWillReceiveProps() {
    const { docDummyStore } = this.props;
    const { dummyId } = this.props.location.query;
    docDummyStore.setDummyId(dummyId);
    const { getConditionInfo, doSearch
      , getTreeData, getchooseDummy } = docDummyStore;
    getTreeData();
    getConditionInfo('Dummy');
    getchooseDummy();
  }
  componentWillUnmount() {
    const { docDummyStore } = this.props;
    const { setTabData, setSelectedTreeKeys, setExpandedKey
      , setShowSearchAd } = docDummyStore;
    setTabData([]);
    setSelectedTreeKeys([], false);
    setExpandedKey([]);
    setShowSearchAd(false);
  }
  onRightMenuClick() {
    const Arr = [];
    return Arr;
  }
  getRightMenu() {
    const { docDummyStore } = this.props;
    const { rightMenu, doSearch, form, showSearchAd
      , setShowSearchAd, comsWeaTableStore
      , setCopyOrMove, setVisible, dummyId
      , quickSearchValue } = docDummyStore;
    let btnArr = [];
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys;
    rightMenu.slice().forEach((m) => {
      let disabled = selectedRowKeys.length === 0;
      let onClick = () => { };
      let content = m.menuName;
      if (m.type === 'BTN_SEARCH') {
        disabled = false;
        onClick = () => {
          if (showSearchAd) {
            doSearch('Dummy', { dummyId, ...form.getFormParams() });
            setShowSearchAd(false);
          } else {
            doSearch('Dummy', { dummyId, docsubject: quickSearchValue });
          }
        };
      } else if (m.type === 'BTN_COPY') {
        onClick = () => {
          setCopyOrMove(false);
          setVisible(true);
        };
      } else if (m.type === 'BTN_MOVE') {
        onClick = () => {
          setCopyOrMove(true);
          setVisible(true);
        };
      } else if (m.type === 'BTN_DELETE') {
        onClick = () => {
          docDummyStore.removeOfDummy({ dummyId, selectIds: selectedRowKeys.join() });
          doSearch('Dummy', { dummyId });
        };
      }
      btnArr.push({
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content,
        disabled,
        onClick,
      });
    });
    return btnArr;
  }
  getButtons() {
    const { docDummyStore } = this.props;
    const { rightMenu, comsWeaTableStore, setCopyOrMove, setVisible } = docDummyStore;
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys;
    let btnArr = [];
    rightMenu.slice().forEach((m) => {
      let onClick = () => { };
      let content = m.menuName;
      let disabled = selectedRowKeys.length === 0;
      if (m.type === 'BTN_COPY') {
        onClick = () => {
          setCopyOrMove(false);
          setVisible(true);
        };
      } else if (m.type === 'BTN_MOVE') {
        onClick = () => {
          setCopyOrMove(true);
          setVisible(true);
        };
      }
      if (m.isTop === '1') {
        btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ikc0mv@${m.type}`} type="primary" disabled={disabled} onClick={onClick}>{content}</Button>);
      }
    });
    return btnArr;
  }
  getRightMenuMove() {
    const { docDummyStore } = this.props;
    const { chooseDummyRM, comsWeaTableStore, copyOrMove
      , dummyId, moveOfDummy, copyOfDummy, formImport } = docDummyStore;
    const formParams = formImport.getFormParams();
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys.join();
    let btnArr = [];
    btnArr.push({
      key: chooseDummyRM.type,
      icon: <i className={chooseDummyRM.menuIcon} />,
      content: chooseDummyRM.menuName,
      disabled: !formParams.dummyIds,
      onClick: () => {
        if (copyOrMove) {
          moveOfDummy({ dummyId, dummyIds: formParams.dummyIds, selectIds: selectedRowKeys });
        } else {
          copyOfDummy({ dummyIds: formParams.dummyIds, selectIds: selectedRowKeys });
        }
      },
    });
    return btnArr;
  }
  getItem = (item, selected) => {
    let getNode = false;
    let returnItem = [];
    if (item.domid === selected) {
      getNode = true;
      returnItem.push({ item, getNode });
    } else {
      returnItem.push({ item, getNode });
      if (item.haschild) {
        item.childs.forEach((i) => {
          let tempResult = [];
          tempResult = this.getItem(i, selected);
          returnItem = returnItem.concat(tempResult);
        });
      }
    }
    return returnItem;
  }
  getShowItem = (tempResult, domid, pid) => {
    let result = [];
    let temp = [];
    tempResult.forEach((item) => {
      if (item.item.domid === domid) {
        result.unshift(item.item);
      }
    });
    tempResult.forEach((item) => {
      if (item.item.key === pid) {
        result.unshift(item.item);
        temp = [];
        if (pid !== '') {
          temp = this.getShowItem(tempResult, item.item.domid, item.item.pid);
          temp.pop();
          result = temp.concat(result);
        }
      }
    });
    return result;
  }
  getItem = (item, selected) => {
    let getNode = false;
    let returnItem = [];
    if (item.domid === selected) {
      getNode = true;
      returnItem.push({ item, getNode });
    } else {
      returnItem.push({ item, getNode });
      if (item.haschild) {
        item.childs.forEach((i) => {
          let tempResult = [];
          tempResult = this.getItem(i, selected);
          returnItem = returnItem.concat(tempResult);
        });
      }
    }
    return returnItem;
  }
  getTree() {
    const { docDummyStore } = this.props;
    const { treeData, selectedTreeKeys, setSelectedTreeKeys
      , expandedKey, getShowItem, setKey, setExpandedKey } = docDummyStore;
    return (
      <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@b126b8`}
        datas={toJS(treeData)}
        expandedKeys={expandedKey.slice()}
        selectedKeys={selectedTreeKeys.slice()}
        onSelect={this.onTreeSelect}
      />
    );
  }
  onTreeSelect=(key) => {
    const { docDummyStore } = this.props;
    const { treeData, setSelectedTreeKeys, setExpandedKey } = docDummyStore;
    setSelectedTreeKeys([key], false);
    let tempExpandedKey = [];
    treeData.forEach((item) => {
      if (item.domid === key) {
        docDummyStore.setKey([item.key]);
        tempExpandedKey.push(key);
      } else if (item.haschild) {
        const tempkey = this.getItem(item, key);
        tempkey.forEach((i) => {
          if (i.getNode) {
            const temptreeData = this.getShowItem(tempkey, i.item.domid, i.item.pid);
            temptreeData.forEach(o => tempExpandedKey.push(o.domid));
            docDummyStore.setKey([`${i.item.key}`]);
          }
        });
      }
    });
    setExpandedKey(tempExpandedKey);
  }
  onSearch = () => {
    const { docDummyStore } = this.props;
    const { form, doSearch, setShowSearchAd, dummyId } = docDummyStore;
    doSearch('Dummy', { dummyId, ...form.getFormParams() });
    setShowSearchAd(false);
  }
  getSearchs() {
    const { docDummyStore } = this.props;
    const { conditioninfo, form } = docDummyStore;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(conditioninfo).map((c, ind) => {
      let items = [];
      c.items.map((fields) => {
        if (fields.isQuickSearch) {
          this.quickSearchPara = fields.domkey[0];
        }
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@q8zh5c@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}
          >
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2t8m4a@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={this.onSearch} />
          </WeaFormItem>),
          colSpan: 1,
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@idb585@${ind}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }
  getMoveItems() {
    const { docDummyStore } = this.props;
    const { chooseDummyCon, formImport } = docDummyStore;
    const { isFormInit } = formImport;
    const formParams = formImport.getFormParams();
    let items = [];
    isFormInit && chooseDummyCon.slice().map((c) => {
      c.items.map((fields) => {
        items.push((<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@g80anw@${fields.domkey[0]}`}
          label={`${fields.label}`}
          labelCol={{ span: `${fields.labelcol}` }}
          wrapperCol={{ span: `${fields.fieldcol}` }}
        >
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7dh542@${fields.domkey[0]}`} fieldConfig={fields} form={formImport} formParams={formParams} />
        </WeaFormItem>));
      });
    });
    return items;
  }
  getTabButtonsAd() {
    const { docDummyStore } = this.props;
    const { form, doSearch, setShowSearchAd, dummyId } = docDummyStore;
    const btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@skgpxn@Search`} type="primary"
        onClick={() => {
          doSearch('Dummy', { dummyId, ...form.getFormParams() });
          setShowSearchAd(false);
        }}
      >{getLabel(197, '搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@annef8@reset`} type="ghost" onClick={() => form.reset()}>{getLabel(2022, '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@peipid@cancel`} type="ghost"
        onClick={() => {
          setShowSearchAd(false);
        }}
      >{getLabel(31129, '取消')}</Button>,
    ];
    return btns;
  }

  getcollectParams() {
    const { docDummyStore } = this.props;
    return {
      favname: docDummyStore.title,
      favouritetype: 2,
      objid: 0,
      importantlevel: 1,
      link: 'wui/index.html#/main/document/dummy',
    }
  }

  getDropMenuProps() {
    const { docDummyStore } = this.props;
    return {
      collectParams: {
        favname: docDummyStore.title,
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/index.html#/main/document/dummy',
      },
    }
  }
  hideSearchAd=() => {
    const{ setShowSearchAd}=this.props.docDummyStore;
    setShowSearchAd(false);
  }
  getSearchsBaseValue = () => {
    const { docDummyStore } = this.props;
    const { form } = docDummyStore;
    return form.getFormParams()[this.quickSearchPara] || '';
  }
  setShowSearchAd=() => {
    const { docDummyStore } = this.props;
    const { setShowSearchAd ,showSearchAd} = docDummyStore;
    setShowSearchAd(!showSearchAd);
  }
  onTabSearch=(value) => {
    const { docDummyStore } = this.props;
    const { doSearch,dummyId } = docDummyStore;
    doSearch('Dummy', { dummyId, docsubject: value });
  }
  onTabSearchChange=(value) => {
    const { docDummyStore } = this.props;
    const { form,setQuickSearchValue } = docDummyStore;
    form.updateFields({ [this.quickSearchPara]: { value } });
    setQuickSearchValue(value);
  }
  onOperatesClick=(record, index, operate) => {
    const{ doSearch, removeOfDummy,dummyId, setCopyOrMove,setVisible}=this.props.docDummyStore;
    const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
    if (funName === 'doRemove') {
      confirm({
        content: (
          <span>
            {getLabel(127574, '确定删除吗？')}
          </span>
        ),
        onOk: () => {
          removeOfDummy({ dummyId, selectIds: record.id });
          doSearch('Dummy', { dummyId });
        },
        onCancel() { },
      });
    } else if (funName === 'doCopy') {
      setCopyOrMove(false); setVisible(true);
    } else if (funName === 'doMove') {
      setCopyOrMove(true); setVisible(true);
    }
  }
  onDummyDiaCancel=() => {
    this.props.docDummyStore.setVisible(false);
    this.props.docDummyStore.formImport.reset();
  }
  onDummyDiaClick=() => {
    const {comsWeaTableStore,copyOrMove,dummyId,formImport,moveOfDummy,copyOfDummy}=this.props.docDummyStore;
    const formParams = formImport.getFormParams();
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys.join();
    if (copyOrMove) {
      moveOfDummy({ dummyId, dummyIds: formParams.dummyIds, selectIds: selectedRowKeys });
    } else {
      copyOfDummy({ dummyIds: formParams.dummyIds, selectIds: selectedRowKeys });
    }
  }
  render() {
    const { docDummyStore } = this.props;
    let { comsWeaTableStore, loading, showSearchAd
      ,  dialogCopy, visible
      ,  formImport, chooseDummyRM, tabData
      , treeData, setSelectedTreeKeys, setDummyId
       } = docDummyStore;
    const loadingNow = loading || comsWeaTableStore.loading;
    const formParams = formImport.getFormParams();
    return (
      <div className="wea-doc-dummy">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@yu2dgx`}
          collectParams={this.getcollectParams()}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@04fxqs`}
            title={docDummyStore.title}
            loading={docDummyStore.loading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            buttons={this.getButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={this.getDropMenuProps}
            onDropMenuClick={this.onRightMenuClick}
          >
            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@ydldfq`} isNew={true} leftCom={this.getTree()} >
              <div style={{ position: 'relative' }}>
                <div className="tabroute">
                  <div className="subroute icon-home">
                    <span className="icon-coms-LargeArea tabicon-home"
                      onClick={() => {
                        setSelectedTreeKeys([toJS(treeData)[0].domid], true);
                      }}
                    />
                  </div>
                  {
                    tabData.map((item, index) => {
                      if (index === tabData.length - 1) {
                        return (
                          <div className="subroute tabcontent">
                            <span className="tabtext"
                              onClick={() => {
                                setSelectedTreeKeys([item.domid], true);
                              }}
                            >{item.name}</span>
                          </div>
                        );
                      }
                      return (
                        <div className="subroute tabcontent">
                          <span className="tabtext"
                            onClick={() => {
                              setSelectedTreeKeys([item.domid], true);
                            }}
                          >{item.name}</span>
                          <span className="icon-coms-organization-right icon-caretright" />
                        </div>
                      );
                    })
                  }
                </div>
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@u8epky`}
                  searchType={this.state.searchType}
                  searchsAd={this.getSearchs()}
                  showSearchAd={showSearchAd}
                  buttonsAd={this.getTabButtonsAd()}
                  hideSearchAd={this.hideSearchAd}
                  searchsBaseValue={this.getSearchsBaseValue()}
                  setShowSearchAd={this.setShowSearchAd}
                  onSearch={this.onTabSearch}
                  onSearchChange={this.onSearchChange}
                />
              </div>
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@z252bk`}
                comsWeaTableStore={comsWeaTableStore}
                hasOrder={true}
                needScroll={true}
                showmethod={true}
                onOperatesClick={this.onOperatesClick}
              />
            </WeaLeftRightLayout>
          </WeaTop>
        </WeaRightMenu>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@9h44zl`}
          className="wea-doc-dummy-dialog"
          visible={visible}
          {...dialogCopy}
          onCancel={this.onDummyDiaCancel}
        >
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@vgcxku`} datas={this.getRightMenuMove()}>

            {this.getMoveItems()}
            <div className="wea-doc-dummy-dialog-btn">
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i8uu5r`} type="primary"
                disabled={!formParams.dummyIds}
                onClick={this.onDummyDiaClick}
              >{chooseDummyRM.menuName}</Button>
              <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@zowbfq`} datas={this.getRightMenuMove()} />
            </div>

          </WeaRightMenu>
        </WeaDialog>
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@5t607d`} pathname="/document/dummy" secid="-1" docid="-1" />
      </div>
    );
  }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@jt6cjj`} msg={props.error ? props.error : getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)(Dummy);

